package com.atguigu.gmall.pay.api;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.pay.config.AppAlipayConfig;
import com.atguigu.gmall.pay.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/payment")
public class PayListener {

    @Autowired
    OrderFeignClient orderFeignClient;
    @Autowired
    AppAlipayConfig appAlipayConfig;
    @Autowired
    PayService payService;

    /**
     * 支付成功的异步回调
     * @param vo
     * @param request
     * @return
     */
    @PostMapping("/pay/success/notify")
    public String paySuccess(PayResponseVo vo , HttpServletRequest request) throws Exception {
        //验证签名
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                appAlipayConfig.alipay_public_key,
                appAlipayConfig.charset,
                appAlipayConfig.sign_type); //调用SDK验证签名

        if (signVerified){
            log.info("验证签名成功.....");
            if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED") ){
                //修改订单状态
                orderFeignClient.changeOrderStatusPayed(vo.getOut_trade_no());
                //发送消息给库存服务，让它减库存
                payService.sendPaySuccessMessage(vo.getOut_trade_no());
            }

            System.out.println("支付宝带来的数据："+vo);
            return "success";
        }
        return "验证失败";
    }
}
